import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

//replace重写
//先获取原replace方法进行接收
const originReplace = VueRouter.prototype.replace;
//重写replace方法 抛出异常
VueRouter.prototype.replace = function replace(location) {
    return originReplace.call(this, location).catch((error) => error);
};
const originPush = VueRouter.prototype.push;
//重写push
VueRouter.prototype.push = function push(location) {
    return originPush.call(this, location).catch((error) => error);
};
//引入cookie
import { getCookie } from '@/utils/cookie'
//引入路由routes
import routes from '@/router/config'
//引入api
import { getMenus } from '@/network/api/article'
//引入h5缓存
import { setStorage } from '@/utils/html5'
import store from '@/store'
//实例化路由
// ...mapMutations('article', {
//     add_router:'add_history'
// })
const router = new VueRouter({
    mode: 'history',
    routes: routes,
    //路由回退,回退到原来的位置
    scrollBehavior(to, from, savePosition) {
        if (savePosition) {
            return savePosition
        }
        return { x: 0, y: 0 }
    }
})


//设置路由守卫白名单
const whiteList = ['/login']
//定义空菜单
let sysMenus = null;
//路由前置守卫
router.beforeEach(async (to, from, next) => {
    const token = getCookie('_token')
    if (whiteList.indexOf(to.path) != -1) {
        if (token) {
            if (to.path == "/login") {
                next({ path: '/' })
            }
        }
        next()
    } else {
        if (!token) {
            next({ path: '/login', query: { redirect: to.path } })
        } else {
            if (!sysMenus) {
                //获取菜单数据
                sysMenus = await getSysMenus()

                //处理菜单
                //解析数据---返回解析之后的路由配置
                let routess = compilerComponent(sysMenus);
                routess[0].children[0].path = '/dashboard/dashboard';
                routess[0].children[0].component = () => import(`@/views/dashboard/dashboard.vue`);

                setStorage("_menu", routess)
                routess.forEach(item => {
                    item.children.forEach(element => {
                        // if (element.path == '/dashboard') {
                        //     element.path = '/dashboard/dashboard'
                        // }
                        router.addRoute("主页", element)
                    });
                });
                next({ path: "/" });
            } else {
                store.commit('article/add_history', {
                    name: to.name,
                    path: to.path,
                    isNow: true,
                })
                next()
            }
        }
    }
})
//处理业务的地方

//获取菜单数据
async function getSysMenus() {
    let res = await getMenus()
    return res.data.data
}

//处理数据菜单的地方
function compilerComponent(sysMenus) {
    let routes = [];
    sysMenus.forEach(item => {

        let routerInfo = {
            path: item.component,
            icon: item.icon,
            title: item.name,
            name: item.name,
            //设置组件懒加载
            component: loadComponent(item.component),
            meta: {
                title: item.name,
            }
        }
        if (item.childList && item.childList != 0) {
            routerInfo.children = compilerComponent(item.childList);
        }
        routes.push(routerInfo)
    });

    return routes
}

function loadComponent(url) {
    if (url == '/dashboard') {
        //url上存在/***  完整路径
        //views  后不建议写 /
        return () => import(`@/views/dashboard${url}.vue`);
        console.log(url);

    } else {
        return () => import(`@/views${url}.vue`);

    }
}
export default router